package com.zhiwang.planet.service

import android.annotation.SuppressLint
import android.app.DownloadManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.IBinder
import android.util.Log
import androidx.core.content.FileProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.foo.CallBack
import com.zhiwang.planet.ui.interf.UiProgress
import com.zhiwang.planet.util.MD5
import java.io.File


class DownLoadService : Service() {
    companion object {

        val URL_KEY = "URL"

        val MD5_KEY = "MD5"

        private var dm: DownloadManager? = null

        private var downloadId: Long = 0

        @SuppressLint("StaticFieldLeak")
        var materialDialog: UiProgress? = null

        var downloadCompleteListener: CallBack? = null


        fun start(context: Context, url: String, md5: String) {
            val service = Intent(context, DownLoadService::class.java)
            service.putExtra(URL_KEY, url)
            service.putExtra(MD5_KEY, md5)
            context.startService(service)
        }

        fun start(context: Context, url: String, md5: String, downloadCompleteCallBack: CallBack) {
            downloadCompleteListener = downloadCompleteCallBack
            val service = Intent(context, DownLoadService::class.java)
            service.putExtra(URL_KEY, url)
            service.putExtra(MD5_KEY, md5)
            context.startService(service)
        }

        fun stopDownload() {
            dm?.remove(downloadId)
        }

    }


    //"content://downloads/my_downloads"必须这样写不可更改
    val CONTENT_URI = Uri.parse("content://downloads/my_downloads")
    private var downloadObserver: DownloadChangeObserver? = null


    private lateinit var md5: String


    private var receiver: BroadcastReceiver? = null

    var file = File(Environment.getExternalStorageDirectory().toString() + "/download/planet.apk")


    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

        receiver = object : BroadcastReceiver() {

            override fun onReceive(context: Context, intent: Intent) {
                var intent = intent
                val longExtra = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                if (longExtra == downloadId) {
                    val fileMd5 = com.zhiwang.planet.util.MD5.getMD5(file)
                    if (this@DownLoadService.md5.toUpperCase() == fileMd5) {
                        intent = Intent(Intent.ACTION_VIEW)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
                            intent.setDataAndType(Uri.fromFile(file.getAbsoluteFile()),
                                    "application/vnd.android.package-archive")
                        else {
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                            intent.setDataAndType(FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file),
                                    "application/vnd.android.package-archive")
                        }
                        startActivity(intent)

                        downloadCompleteListener?.onCallBack()
                    }
                    stopSelf()
                }
            }
        }
        registerReceiver(receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
        val url = intent.getStringExtra(URL_KEY)
        md5 = intent.getStringExtra(MD5_KEY)
        startDownload(url)
        return Service.START_STICKY
    }

    override fun onDestroy() {
        unregisterReceiver(receiver)
        super.onDestroy()
    }

    private fun startDownload(url: String) {
        if (file.exists()) {
            file.delete()
        }
        dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
        val request = DownloadManager.Request(
                Uri.parse(url))
        request.setMimeType("application/vnd.android.package-archive")
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "planet.apk")
        downloadId = dm!!.enqueue(request)
        downloadObserver = DownloadChangeObserver(null)
        contentResolver.registerContentObserver(CONTENT_URI, true, downloadObserver)
    }

    val TAG = "DownLoadService"

    //用于显示下载进度
    private inner class DownloadChangeObserver(handler: Handler?) : ContentObserver(handler) {

        override fun onChange(selfChange: Boolean) {
            val query = DownloadManager.Query()
            query.setFilterById(downloadId)
            val dManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            val cursor = dManager.query(query)
            if (cursor != null && cursor.moveToFirst()) {
                val totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
                val currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
                val totalSize = cursor.getInt(totalColumn)
                val currentSize = cursor.getInt(currentColumn)
                val percent = currentSize.toFloat() / totalSize.toFloat()
                val progress = Math.round(percent * 100)
                Log.i(TAG, "onChange:$downloadId  $totalSize  $currentSize $progress")
                materialDialog?.setUiProgress(progress)
                if (progress == 100) {
                    materialDialog?.onUiComplete()
                    contentResolver.unregisterContentObserver(this)
                }
            }
            cursor.close()
        }


    }
}